﻿


using IotClientService.Models.Lg.Remote;
using IotClientService.Models.Lg;
using IotContract.Dtos.Servers.Process;
using IotContract.Interfaces.Process;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Extensions;
using XT.Common.Services;
using IotContract.Enums;
using IotContract.Extensions;
using IotContract.Models.Clients.Hks;
using IotServerService.Services;
using IotContract.Interfaces;
using IotClientService.Extensions;
using IotContract.Dtos.Remotes.Request;
using IotContract.Dtos.Remotes.Response;
using IotContract.Dtos.Servers.Process.F29;
using XT.Common.Models.Server;
using IotContract.Models.Jobs.F29;

namespace IotClientService.Services;
/// <summary>
/// 调度通用api服务
/// </summary>
public class ProcessApiHandleService :ApiConfigService, IProcessApiHandle
{
    private ILogService _logService;
    private DbService _dbService;
    private string _apiHead = "fms/api/process";
    
    
    public ProcessApiHandleService(IHttpClientFactory httpClientFactory, ILogService logService, DbService dbService,IConnectDataService connectDataService) : base(httpClientFactory)
    {
        _logService = logService;
        _dbService = dbService;
        RemoteApiUrl = connectDataService.AddressConfig.ApiUrl;
    }

   


  
    #region 通用接口方法
    /// <summary>
    /// 验证进入托盘
    /// </summary>
    /// <param name="equipNum"></param>
    /// <param name="equipType"></param>
    /// <param name="tray"></param>
    /// <returns></returns>
    public async Task<AdminCodeResult<string>> ValidateEnterTray(string equipNum, IotEquipType equipType, string tray)
    {
        LgTrayEnterRequest lgTrayEnter = new LgTrayEnterRequest
        {
            Tray = tray,
            EquipNum = equipNum,
            EquipType = equipType
        };
        await _logService.LogContent($"Begin Tray Enter,tray {lgTrayEnter.Tray}", XT.Common.Enums.LogEnum.Info, lgTrayEnter.EquipNum, lgTrayEnter.EquipType.ToString());
        var client = CreateHttpClient();
        string url = $"{_apiHead}/validate-enter-tray";
        var result = await client.PostAdminData<string>(url, this, lgTrayEnter);
        if (!result.Success)
        {
            await _logService.LogContent($"Error Tray Enter,tray {lgTrayEnter.Tray}", XT.Common.Enums.LogEnum.Error, lgTrayEnter.EquipNum, lgTrayEnter.EquipType.ToString(), true);
        }

        return result;
    }

    /// <summary>
    /// 验证托盘出去
    /// </summary>
    /// <param name="equipNum"></param>
    /// <param name="equipType"></param>
    /// <param name="tray"></param>
    /// <returns></returns>
    public async Task<AdminCodeResult<string>> ValidateOutTray(string equipNum, IotEquipType equipType, string tray)
    {
        LgTrayOutRequest lgTrayOut = new LgTrayOutRequest
        {
            Tray = tray,
            EquipNum = equipNum,
            EquipType = equipType
        };
        await _logService.LogContent($"Begin Tray Out,tray {lgTrayOut.Tray}", XT.Common.Enums.LogEnum.Info, lgTrayOut.EquipNum, lgTrayOut.EquipType.ToString());
        var client = CreateHttpClient();
        string url = $"{_apiHead}/validate-out-tray";
        var result = await client.PostAdminData<string>(url, this, lgTrayOut);
        if (!result.Success)
        {
            await _logService.LogContent($"Error Tray Out,tray {lgTrayOut.Tray}", XT.Common.Enums.LogEnum.Error, lgTrayOut.EquipNum, lgTrayOut.EquipType.ToString(), true);

        }

        return result;
    }
    /// <summary>
    /// 提交叠盘完成
    /// </summary>
    /// <param name="tagNumber"></param>
    /// <returns></returns>
    public async  Task<AdminCodeResult<string>> CommitStackOver(int tagNumber)
    {
        await _logService.LogContent($"begin commit stack over,tagNumber {tagNumber}", XT.Common.Enums.LogEnum.Info, tagNumber.ToString(), IotEquipType.CV.ToString());

        var client = CreateHttpClient();
        string url = $"{_apiHead}/commit-stack-over?tagnumber={tagNumber}";
        var result = await client.PostAdminData<string>(url, this);
        if (!result.Success)
        {
            await _logService.LogContent($"Error commit stack over,tagNumber {tagNumber}", XT.Common.Enums.LogEnum.Error, tagNumber.ToString(), IotEquipType.CV.ToString(), true);

        }
        return result;
    }
    /// <summary>
    /// 完成任务
    /// </summary>
    /// <param name="jobId"></param>
    /// <returns></returns>
    public async Task<AdminCodeResult<string>> CompleteJob(string jobId,string jobId2)
    {
        await _logService.LogContent($"Begin CompleteJob,jobid {jobId} jobid2 {jobId2}", XT.Common.Enums.LogEnum.Info, jobId, IotEquipType.STACKER.ToString());

        var client = CreateHttpClient();
        string url = $"{_apiHead}/complete-job";
        var result = await client.PostAdminData<string>(url, this,new FmsJobCompleteRequest { TaskNumberId=jobId,TaskNumberId2=jobId2});
        if (!result.Success)
        {
            await _logService.LogContent($"Error CompleteJob,jobid {jobId} jobid2 {jobId2}", XT.Common.Enums.LogEnum.Error, jobId, IotEquipType.STACKER.ToString(), true);

        }
        return result;
    }

    /// <summary>
    /// 扫描后提交托盘
    /// </summary>
    /// <param name="unit"></param>
    /// <returns></returns>
    public async Task<AdminCodeResult<CvTrayTask>> CommitTrays(FmsCommitTrayRequest unit)
    {
        await _logService.LogContent($"begin commit tray,tagNumber {unit.TagNumber},taskNo {unit.TaskNo},tray {unit.Trays.FirstOrDefault()}", XT.Common.Enums.LogEnum.Info, unit.TagNumber.ToString(), IotEquipType.CV.ToString());
        var client = CreateHttpClient();
        string url = $"{_apiHead}/commit-trays";
        var result = await client.PostAdminData<CvTrayTask>(url, this,unit);

        if (result.Success)
        {
            await _logService.LogContent($"commit tray success,tagNumber {unit.TagNumber},taskNo {unit.TaskNo},tray {unit.Trays.FirstOrDefault()}, returnTask {result.Result.TaskNum},returnDest {result.Result.Dest}", XT.Common.Enums.LogEnum.Info, unit.TagNumber.ToString(), IotEquipType.CV.ToString());
            return result;

        }
        else
        {

            await _logService.LogContent($"Error commit tray ,tagNumber {unit.TagNumber},taskNo {unit.TaskNo},msg {result.Message}", XT.Common.Enums.LogEnum.Error, unit.TagNumber.ToString(), IotEquipType.CV.ToString(), true);
            return result;
        }


    }

    /// <summary>
    /// 站台提交扫码
    /// </summary>
    /// <param name="unitGroup"></param>
    /// <returns></returns>
    public async Task<AdminCodeResult<F29EnterJob>> CommitEnterTrays(FmsCommitTrayRequest unitGroup)
    {
        int tagNumber = unitGroup.TagNumber;
       
        int taskNo = unitGroup.TaskNo;

        if (tagNumber == 0)
        {
            tagNumber = unitGroup.TagNumber2;
            taskNo = unitGroup.TaskNo2;
        }

        await _logService.LogContent($"enter tag begin commit tray,tagNumber {tagNumber},taskNo {taskNo}", XT.Common.Enums.LogEnum.Info, tagNumber.ToString());
        var client = CreateHttpClient();
        string url = $"{_apiHead}/commit-enter-trays";
        var result = await client.PostAdminData<F29EnterJob>(url,this, unitGroup);

        if (result.Success)
        {
            await _logService.LogContent($"commit tray success,tagNumber {tagNumber},taskNo {taskNo}", XT.Common.Enums.LogEnum.Info, tagNumber.ToString());
          

        }
        else
        {
          

            await _logService.LogContent($"commit tray error,tagNumber {tagNumber} ,taskNo  {taskNo}", XT.Common.Enums.LogEnum.Error, tagNumber.ToString());
            
        }
        return result;
    }


   




    #endregion


    #region 通用Sql能力，本地表中的数据，不需要调用api
    /// <summary>
    /// 获取所有入库站台
    /// </summary>
    /// <returns></returns>
    public async Task<AdminCodeResult<List<EnterTagGroupDto>>> GetEnterTags()
    {
        var enterResult = await new Func<Task<List<EnterTagGroupDto>>>(() => _dbService.GetEnterTags()).ProtectFunc();
        var admin=new AdminCodeResult<List<EnterTagGroupDto>>();
        if (enterResult.Item2.IsNotNullOrEmpty())
        {
            admin.Success = false;
            
            await _logService.LogContent("Error can not get enter tags " + enterResult.Item2, XT.Common.Enums.LogEnum.Error, "", "GetEnterTags", true);

        }
        else
        {
            admin.Success = true;
            admin.Result = enterResult.Item1;
            _logService.Log("get enter tags " + enterResult.Item1?.Count);
            
        }

        return admin;
            



    }

    public async Task<AdminCodeResult<string>> ValidateCebEnterTray(FmsTrayRequest fmsTray)
    {
        await _logService.LogContent($"Begin Ceb Enter,tray {fmsTray.Tray},Empty {fmsTray.EmptyTray}", XT.Common.Enums.LogEnum.Info, fmsTray.EquipNum, IotEquipType.CEB.ToString());

        var client = CreateHttpClient();
        string url = $"{_apiHead}/validate-ceb-enter-tray";
        var result = await client.PostAdminData<string>(url,this, fmsTray);

        if (!result.Success)
        {
            await _logService.LogContent($"Error Ceb Enter,tray {fmsTray.Tray},Empty {fmsTray.EmptyTray},{result.Message}", XT.Common.Enums.LogEnum.Error, fmsTray.EquipNum, IotEquipType.CEB.ToString(), true);
        }
        return result;
    }

    public async Task<AdminCodeResult<string>> ValidateCebOutTray(FmsTrayRequest fmsTray)
    {
        await _logService.LogContent($"Begin Ceb Out,tray {fmsTray.Tray},Empty {fmsTray.EmptyTray}", XT.Common.Enums.LogEnum.Info, fmsTray.EquipNum, IotEquipType.CEB.ToString());

        var client = CreateHttpClient();
        string url = $"{_apiHead}/validate-ceb-out-tray";
        var result = await client.PostAdminData<string>(url,this, fmsTray);

        if (!result.Success)
        {
            await _logService.LogContent($"Error Ceb Out,tray {fmsTray.Tray},Empty {fmsTray.EmptyTray},{result.Message}", XT.Common.Enums.LogEnum.Error, fmsTray.EquipNum, IotEquipType.CEB.ToString(), true);
        }

        return result;
    }

    public async Task<AdminCodeResult<List<FMTCell>>> GetCebChannel(FmsTrayRequest fmsTray)
    {
        await _logService.LogContent($"Begin Get CebChannel,tray {fmsTray.Tray}", XT.Common.Enums.LogEnum.Info, fmsTray.EquipNum, IotEquipType.CEB.ToString());

        var client = CreateHttpClient();
        string url = $"{_apiHead}/ceb-channel";
        var result = await client.PostAdminData<List<FMTCell>>(url,this, fmsTray);

        if (!result.Success)
        {
            await _logService.LogContent($"Error Get CebChannel,tray {fmsTray.Tray},{result.Message}", XT.Common.Enums.LogEnum.Error, fmsTray.EquipNum, IotEquipType.CEB.ToString(), true);
        }
        return result;
    }

    public async Task<AdminCodeResult<string>> CebWorkDoneInform(FmsTrayRequest fmsTray)
    {
        await _logService.LogContent($"Begin Ceb Done,tray {fmsTray.Tray},Empty {fmsTray.EmptyTray}", XT.Common.Enums.LogEnum.Info, fmsTray.EquipNum, IotEquipType.CEB.ToString());

        var client = CreateHttpClient();
        string url = $"{_apiHead}/ceb-work-done-inform";
        var result = await client.PostAdminData<string>(url,this, fmsTray);

        if (!result.Success)
        {
            await _logService.LogContent($"Error Ceb Done,tray {fmsTray.Tray},Empty {fmsTray.EmptyTray},{result.Message}", XT.Common.Enums.LogEnum.Error, fmsTray.EquipNum, IotEquipType.CEB.ToString(), true);
        }

        return result;
    }

    #endregion
}
